//
//  XNTimerUIHelper.m
//  xndm_proj
//
//  Created by xn on 2021/5/10.
//  Copyright © 2021 Linfeng Song. All rights reserved.
//

#import "XNTimerUIHelper.h"
#import "HJTDateTool.h"

@implementation XNTimerUIHelper
{
    dispatch_source_t _timer;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.duration = 1;
    }
    return self;
}

- (void)startWithSeconds:(NSInteger)seconds {
    self.seconds = seconds;
    [self startCountDown];
}

#pragma mark - CountDown
- (void)startCountDown{
    if (self.progressBlock) {
        self.progressBlock(self, XNTimeLabelStateStart, self.seconds);
    }
    
    __block NSInteger timeout = self.seconds - self.duration;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        NSString *text;
        XNTimeLabelState state = timeout<=0?XNTimeLabelStateFinish:XNTimeLabelStateDuration;
        if (self.progressBlock) {
            text = self.progressBlock(self, state, timeout);
        }
        else {
            text = [HJTDateTool dateForFormatWithTimeStamp:[NSString stringWithFormat:@"%zd",timeout] withFormat:@"HH:mm:ss"];
        }
        !self.showTextBlock? :self.showTextBlock(text);
        if(timeout<=0){
            if (self->_timer) {
                dispatch_source_cancel(self->_timer);
            }
            return;
        }
        
        timeout--;
    });
    dispatch_resume(_timer);
}

- (void)cancelTimer;
{
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

@end
